package com.bountytask.controller;
import com.alibaba.fastjson.JSONObject;
import com.bountytask.config.ScheduledTasks;
import com.bountytask.config.WebSocketServer;
import com.bountytask.entity.Task;
import com.bountytask.service.InformationService;
import com.bountytask.service.TaskService;
import com.bountytask.service.UserAndTaskService;
import com.bountytask.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@RestController
@Slf4j
public class TaskController {
    @Autowired
    private TaskService taskService;

    @Autowired
    private InformationService informationService;

    @Autowired
    private UserAndTaskService userAndTaskService;

    @Autowired
    private UserService userService;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private ScheduledTasks scheduledTasks;

    //条件搜索，任务排序
    @PostMapping("/task/selectsort")
    public JSONObject taskSort(@RequestBody JSONObject recData){
        List<Task> tasks=taskService.getTasksByCondition(
                recData.getString("keyword"),
                recData.getString("category"),
                recData.getString("campus"));
        String condition = recData.getString("condition");
        if(condition == null) condition = "null";
        JSONObject resultJson = new JSONObject(true);
        resultJson.put("code",200);
        resultJson.put("message","成功");
        resultJson.put("data",taskService.sortTasks(tasks, condition));
        return resultJson;
    }

    //发布任务
    @PostMapping("/task/publish")
    public JSONObject publishTask(@RequestBody JSONObject recData){
        Task newTask = new Task();
        newTask.setTitle(recData.getString("title"));
        newTask.setIllustrate(recData.getString("illustrate"));
        newTask.setBounty(recData.getFloat("bounty"));
        newTask.setTaskNumber(recData.getInteger("tasknumber"));
        newTask.setDeadline(recData.getDate("deadline"));
        newTask.setRequest(recData.getString("request"));
        newTask.setContact(recData.getString("contact"));
        newTask.setLabel(recData.getString("label"));
        newTask.setTotal(recData.getFloat("total"));
        newTask.setCategory(recData.getString("category"));
        JSONObject resultJson = new JSONObject(true);
        JSONObject data = new JSONObject(true);
        //文本检测
        if (scheduledTasks.getAccessToken()==null)
            scheduledTasks.getAccessTokenUrl();
        String checkText=newTask.getTitle()+","+newTask.getIllustrate()+","+newTask.getContact()+","+newTask.getLabel();
        String url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + scheduledTasks.getAccessToken();
        //创建客户端
        HttpClient httpclient = HttpClients.createDefault();
        //创建一个post请求
        HttpPost request = new HttpPost(url);
        //设置响应头
        request.setHeader("Content-Type", "application/json;charset=UTF-8");
        //通过fastJson设置json数据
        JSONObject postData = new JSONObject();
        //设置要检测的内容
        postData.put("content", checkText);
        postData.put("version",2);
        postData.put("scene",2);
        postData.put("openid",userService.getUserById(recData.getLong("userid")).getOpenId());
        String jsonString = postData.toString();
        request.setEntity(new StringEntity(jsonString,"utf-8"));
        try {
            HttpResponse response = httpclient.execute(request);
            // 从响应模型中获取响应实体
            HttpEntity entity = response.getEntity();
            //得到响应结果
            String result = EntityUtils.toString(entity,"utf-8");
            JSONObject resultJsonObject = JSONObject.parseObject(result);

            JSONObject res= resultJsonObject.getJSONObject("result");
            int label = Integer.parseInt(res.getString("label"));
            if(label!=100){//当content内含有敏感信息，则返回87014
                resultJson.put("code",label);
                switch (label){
                    case 10001:resultJson.put("message","广告");break;
                    case 20001:resultJson.put("message","政治敏感");break;
                    case 20002:resultJson.put("message","色情");break;
                    case 20003:resultJson.put("message","辱骂");break;
                    case 20006:resultJson.put("message","违法犯罪");break;
                    case 20008:resultJson.put("message","欺诈");break;
                    case 20012:resultJson.put("message","低俗");break;
                    case 20013:resultJson.put("message","版权");break;
                    case 21000:resultJson.put("message","其它违规");
                }
                return resultJson;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        long flag=taskService.postTask(newTask,recData.getLong("userid"));
        if(flag==0){
            resultJson.put("code",400);
            resultJson.put("message","余额不足");
        }
        else if (flag==-1){
            resultJson.put("code",500);
            resultJson.put("message","添加失败");
        }
        else {
            resultJson.put("code",200);
            resultJson.put("message","成功");
            data.put("id",flag);
            resultJson.put("data",data);
        }
        return resultJson;
    }

    @PostMapping("/task/take")
    public JSONObject takeTask(@RequestBody JSONObject recData) throws IOException {
        int flag=taskService.takeTaskService(recData.getLong("userid"),recData.getLong("taskid"));
        JSONObject resultJson = new JSONObject();
        if (flag == 404)
            resultJson.put("message","任务已下线");
        else if (flag == 401)
            resultJson.put("message","没有可以领取的任务");
        else if (flag == 400)
            resultJson.put("message","领取失败");
        else {
            resultJson.put("message","领取成功");
            long posterId=userAndTaskService.getPoster(recData.getLong("taskid"));
            webSocketServer.
                    sendMessageList(informationService.getInfo(1,
                    informationService.addInformation
                            (1,1,recData.getLong("taskid"),posterId)),posterId);
        }
        resultJson.put("code",flag);
        return resultJson;
    }

    @GetMapping("/task/get/{id}")
    public JSONObject getTaskById(@PathVariable long id){
        JSONObject resultJson = new JSONObject(true);
        Task task = taskService.getTaskById(id);
        if (task==null){
            resultJson.put("code",400);
            resultJson.put("message","失败");
            return resultJson;
        }
        resultJson.put("code",200);
        resultJson.put("message","成功");
        resultJson.put("data",task);
        return resultJson;
    }

    @PutMapping("/task/modify")
    public JSONObject updateTask(@RequestBody Task task){
        JSONObject resultJson = new JSONObject(true);
        //重置任务发布时间
        task.setStartTime(new Date());
        int flag=taskService.updateTask(task);
        if (flag==400){
            resultJson.put("code",flag);
            resultJson.put("message","失败");
            resultJson.put("data",task);
            return resultJson;
        }
        resultJson.put("code",flag);
        resultJson.put("message","成功");
        resultJson.put("data",task);
        return resultJson;
    }

    /**
     * 认定无效
     */
    @PutMapping("/task/reject")
    public JSONObject rejectTask(@RequestBody JSONObject recData)throws IOException{
        JSONObject jsonObject=new JSONObject(true);
        if(taskService.rejectTask(recData.getLong("taskid"),recData.getLong("userid"))!=200)
        {
            jsonObject.put("code",400);
            jsonObject.put("message","失败");
            return jsonObject;
        }
        webSocketServer.
                sendMessageList(informationService.
                        getInfo(0, informationService.
                                addInformation(0,2,recData.getLong("taskid"),recData.getLong("userid"))),
                                        recData.getLong("userid"));
        jsonObject.put("code",200);
        jsonObject.put("message","成功");
        return jsonObject;
    }
}
